# -*- coding: utf-8 -*-
import maya.cmds as mc
from liberHook.BaseHook import BaseHook
from liberLibs.dccLibs.Maya import load_plugin
from liberLibs.path import Path
import liberConfig

TEXTURE_NODE_ATTR_DICT = liberConfig.TEXTURE_NODE_ATTR_DICT


class Hook(BaseHook):
    def __init__(self, library, directory, ext, start, end):
        BaseHook.__init__(self, library, directory, ext, start, end)

    def execute(self):
        if load_plugin("redshift4maya.mll"):
            light = "RS_ENV_DOME_LIGHTShape"
            if mc.objExists(light) and mc.nodeType(light) == "RedshiftDomeLight":
                node = light
            else:
                node = self.create_dome_light()
            files = Path(self.location).children()
            files = [f for f in files if Path(f).isFile()]
            file_name = files[0]
            attr = "%s.%s" % (node, TEXTURE_NODE_ATTR_DICT.get("RedshiftDomeLight"))
            mc.setAttr(attr, file_name, type="string")
        else:
            self.append_error("Can not load plugin: redshift4maya.mll")

    @staticmethod
    def create_dome_light():
        node = mc.shadingNode("RedshiftDomeLight", asLight=1)
        node = mc.rename(node, "RS_ENV_DOME_LIGHT")
        child = mc.listRelatives(node, c=1)[0]
        child = mc.rename(child, "%sShape" % node)
        mc.setAttr("%s.background_enable" % child, 0)
        return child
